<script setup>
import {getCurrentInstance, reactive, ref, toRefs, watch} from "vue";
import SelectTable from "@/views/lims/contractAnalysis/table/selectTable.vue";
import {LimsConfig} from "@/api/lims/common/LimsModel";
import {deleteFormData, getTableRecord} from "@/api/lims/sysManager/table";
import {toCamKey} from "@/utils/wanfeng";
const {proxy} = getCurrentInstance()
const props = defineProps({
  orderId: {type:String, required: true}
})
const emit = defineEmits(['checked'])
const inspectProjectList = ref([])


const loadInspectProjectList = () => {
  let config = new LimsConfig('M_CONTRACT_ANALYSIS_SUBJECT')
  config.filters.eq('ORDER_ID', props.orderId).orderByAsc('ORDER_INDEX')
  getTableRecord(config).then(response => {
    if (response.success){
      console.log('loadInspectProjectList:::', response)
      inspectProjectList.value = response.data
      emit('checked', inspectProjectList.value)
    }
  })
}
loadInspectProjectList()

const selectTable = ref()

const data = reactive({
  table : {
    tableName: 'MM_PRICE_STANDARD',
    columns:[
      {label:'标识', name: 'ID', isQuery: true},
      {label:'检测项目', name: '检测项目', isQuery: true},
      {label:'所属产品号', name: '所属产品号', isQuery: true},
      {label:'分析方法', name: '分析方法', isQuery: true},
      {label:'方法标准', name: '方法标准', isQuery: true},
      {label:'所需样品', name: '所需样品量', isQuery: true},
      {label:'单价', name: '单价', isQuery: false},
      {label:'序号', name: '序号', isQuery: false},
      {label:'备注', name: '备注', isQuery: false},
      {label:'描述', name: 'PRODUCT_TYPE', isQuery: false},
      {label:'所属部门', name: '所属部门', isQuery: false},
    ],
    height: 450,
  }
})
const {table} = toRefs(data)

const  handleSelectSubjects = () =>{
  selectTable.value.show(table.value)
}

const onSelectedSubjects = (rows) => {
  console.log('select row is ', rows)
  rows.forEach(item => {
    let subject = {
      INSPECT_SUBJECT:item.检测项目,
      METHOD_STANDARD:item.方法标准,
      METHOD_ID:item.分析方法,
      SUBJECT_PRICE: item.单价,
      MEMO:item.备注,
      ORDER_INDEX: inspectProjectList.value.length +1,
      ORDER_ID:props.orderId
    }
    inspectProjectList.value.push(subject)
  })
}
const detailTable = ref()
const upRow = (row, index) => {
  console.log('row', row, 'row.index', index)
  console.log(inspectProjectList.value[index])
  row.ORDER_INDEX = parseInt(row.ORDER_INDEX) -1
  inspectProjectList.value[index-1].ORDER_INDEX = parseInt(inspectProjectList.value[index-1].ORDER_INDEX) +1
  inspectProjectList.value.splice(index,1)
  inspectProjectList.value.splice(index-1, 0, row)
  detailTable.value.setCurrentRow(index+1)

}
const downRow = (row, index) =>{
  row.ORDER_INDEX = parseInt(row.ORDER_INDEX) + 1
  inspectProjectList.value[index+1].ORDER_INDEX = parseInt(inspectProjectList.value[index+1].ORDER_INDEX) - 1
  inspectProjectList.value.splice(index,1)
  inspectProjectList.value.splice(index+1, 0, row)
}
const deleteRow = (row, index) =>{
  //todo 删除时如果ID已存在，需要通过ID进行删除数据
  if (row.ID && row.ID.length > 0){
    let rowData = Object.assign({}, row)
    rowData = toCamKey(rowData)
    deleteFormData('M_CONTRACT_ANALYSIS_SUBJECT', [rowData], false, false).then(response => {
      if (response.success){
        proxy.$modal.msgSuccess('删除成功')
        inspectProjectList.value.splice(index,1)
      }else {
        proxy.$modal.msgError('删除接口信息异常：',response.message)
      }
    })
  }else {
    inspectProjectList.value.splice(index,1)
  }
  resetOrderIndex()
}

const resetOrderIndex = () =>{
  inspectProjectList.value.forEach((value,index) => {
    value.ORDER_INDEX = index+1
  })
}
const editRow = (row) =>{
  row.showInput = true
}
const commitRow= (row) =>{
  row.showInput = false
}
const  handleAddRow = () =>{
  let row = {editAble:true, showInput:true, ORDER_INDEX: inspectProjectList.value.length+1}
  inspectProjectList.value.push(row)
}
const tableRowClassName = (row) =>{
  if (!row.row.ID || row.row.ID.length === 0){
    return 'success-row'
  }
}

const checkBtn = ref()
const handleChecked = () =>{
  emit('checked', inspectProjectList.value)
}

watch(() => inspectProjectList.value, arrayValue => {
  emit('checked', arrayValue)
}, {deep: true})

</script>

<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Search"
            @click="handleSelectSubjects"
        >选择检验项目</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Plus"
            @click="handleAddRow"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            ref="checkBtn"
            type="success"
            plain
            icon="Check"
            @click="handleChecked"
        >确定依据</el-button>
      </el-col>

    </el-row>
    <el-table :data="inspectProjectList" ref="detailTable" show-summary border :row-class-name="tableRowClassName">
      <el-table-column label="序号" prop="ORDER_INDEX"  width="55"/>
      <el-table-column label="检验项目" prop="INSPECT_SUBJECT">
        <template #default="scope">
          <span v-if="!scope.row.showInput">{{scope.row.INSPECT_SUBJECT}}</span>
          <el-input v-else v-model="scope.row.INSPECT_SUBJECT"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="方法标准" prop="METHOD_STANDARD">
        <template #default="scope">
          <span v-if="!scope.row.showInput">{{scope.row.METHOD_STANDARD}}</span>
          <el-input v-else v-model="scope.row.METHOD_STANDARD"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="分析方法" prop="METHOD_ID">
        <template #default="scope">
          <span v-if="!scope.row.showInput">{{scope.row.METHOD_ID}}</span>
          <el-input v-else v-model="scope.row.METHOD_ID"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单项价格" prop="SUBJECT_PRICE">
        <template #default="scope">
          <span v-if="!scope.row.showInput">{{scope.row.SUBJECT_PRICE}}</span>
          <el-input v-else v-model="scope.row.SUBJECT_PRICE"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="MEMO">
        <template #default="scope">
          <span v-if="!scope.row.showInput">{{scope.row.MEMO}}</span>
          <el-input v-else v-model="scope.row.MEMO"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button icon="Top" type="primary" :disabled="scope.$index === 0" circle @click="upRow(scope.row, scope.$index)"></el-button>
          <el-button icon="Bottom" type="info" :disabled="scope.$index === inspectProjectList.length-1" circle @click="downRow(scope.row, scope.$index)"></el-button>
          <el-button icon="Delete" circle type="danger" @click="deleteRow(scope.row)"></el-button>
          <el-button icon="Edit" circle v-if="!scope.row.showInput" type="primary" @click="editRow(scope.row)"></el-button>
          <el-button icon="Finished" circle v-else-if="scope.row.showInput" type="success" @click="commitRow(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <select-table ref="selectTable" :selection="true" @ok="onSelectedSubjects"></select-table>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-table .success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>